package com.ruoyi.quartz.uniController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.AddWechat;
import com.ruoyi.system.domain.AuditRecords;
import com.ruoyi.system.domain.BeseImg;
import com.ruoyi.system.domain.ManualAuditPage;
import com.ruoyi.system.enumutil.AddWechatEnum;
import com.ruoyi.system.enumutil.AuditRecordsEnum;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.AddWechatService;
import com.ruoyi.system.service.AuditRecordsService;
import com.ruoyi.system.service.ManualAuditPageService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Objects;

import java.util.Base64;
import java.util.UUID;


/*
 *  @author 雨安
 *  类名： ConnectionsController
 *  创建时间：2025/2/13
 *  小程序人脉界面
 */
@RestController
@RequestMapping("/uni/connections")
public class ConnectionsController {

    @Resource
    private AddWechatService addWechatService;

    @Resource
    private AuditRecordsService auditRecordsService;

    @PostMapping("/get/add/wechat")
    public AjaxResult getAddWechat(@RequestBody AddWechat addWechat, HttpServletRequest request){
        System.out.println(addWechat + "我是测试sss");
        //创建分页对象
        Page<AddWechat> page = new Page<>();
        //设置页码
        page.setCurrent(addWechat.getCurrent());
        //设置行数
        page.setSize(addWechat.getSize());
        //查询数据
        addWechatService.page(page,new LambdaQueryWrapper<AddWechat>()
                //审核通过
                .eq(AddWechat::getStatus, AddWechatEnum.ShenHeTongGuo.getStatus())
                //需求人数大于 0
                .gt(AddWechat::getNeedCount, 0)
                //逻辑删除
                .eq(AddWechat::getDeleteFlag,Boolean.FALSE)
                //添加分页语句
                .last(" limit " + (addWechat.getCurrent() - 1) * addWechat.getSize() +"," + addWechat.getSize())
                //创建时间
                .orderByDesc(AddWechat::getCreateTime)
                //添加分页语句
//                .last(" limit " + (addWechat.getCurrent() - 1) * addWechat.getSize() +"," + addWechat.getSize())
        );
        //设置总行数
        page.setTotal(addWechatService.count(new LambdaQueryWrapper<AddWechat>()
                //审核通过
                .eq(AddWechat::getStatus, AddWechatEnum.ShenHeTongGuo.getStatus())
                //需求人数大于 0
                .gt(AddWechat::getNeedCount, 0)
                //逻辑删除
                .eq(AddWechat::getDeleteFlag,Boolean.FALSE)
        ));
        String token = request.getHeader("Authorization");
        System.out.println(token + "我是测试");
        //遍历集合数据
        page.getRecords().stream().forEach(ele->{
            //判断用户是否为只允许薅羊毛一次
            SysUser sysUser = sysUserMapper.selectUserById(ele.getUserId());
            //判断是否为薅羊毛一次
            if (sysUser.getPickType() == 1 && StringUtils.isNotBlank(token)){
                //查询当前用户是否有该任务完成情况
                AuditRecords auditRecords = auditRecordsService.getOne(new LambdaQueryWrapper<AuditRecords>()
                        //完成任务用户id
                        .eq(AuditRecords::getUserId, SecurityUtils.getUserId())
                        //任务发布用户编号
                        .eq(AuditRecords::getAddWechatUserId,ele.getUserId())
                        //审核结果
                        .eq(AuditRecords::getAddStatus, AuditRecordsEnum.ShenHeTongGuo.getStatus())
                        //逻辑删除
                        .eq(AuditRecords::getDeleteFlag, Boolean.FALSE)
                        //查询一条即可
                        .last("limit 1")
                );
                //判断用户做该任务是否有结果
                if (Objects.nonNull(auditRecords)){
                    System.out.println(sysUser.getNickName() + "我进入了此处======");
                    //设置状态
                    ele.setUserRecordsType(Boolean.TRUE);
                }else{
                    //设置为没有该奖励
                    ele.setUserRecordsType(Boolean.FALSE);
                }
            }else if (StringUtils.isNotBlank(token)){
                //查询当前用户是否有该任务完成情况
                AuditRecords auditRecords = auditRecordsService.getOne(new LambdaQueryWrapper<AuditRecords>()
                        //完成任务用户id
                        .eq(AuditRecords::getUserId, SecurityUtils.getUserId())
                        //任务id
                        .eq(AuditRecords::getAddWechatId, ele.getId())
                        //审核结果
                        .eq(AuditRecords::getAddStatus, AuditRecordsEnum.ShenHeTongGuo.getStatus())
                        //逻辑删除
                        .eq(AuditRecords::getDeleteFlag, Boolean.FALSE)
                );
                //判断用户做该任务是否有结果
                if (Objects.nonNull(auditRecords)){
                    //设置状态
                    ele.setUserRecordsType(Boolean.TRUE);
                }else{
                    //设置为没有该奖励
                    ele.setUserRecordsType(Boolean.FALSE);
                }
            }else{
                //此处为没有登录的用户
                ele.setUserRecordsType(Boolean.FALSE);
            }
        });
        //返回结果
        return AjaxResult.success(page);
    }

    @Resource
    private ManualAuditPageService manualAuditPageService;


    //查询
    @PostMapping("/get/ManualAuditPage")
    public AjaxResult getManualAuditPage(){
        System.out.println("我是测试sss");
        //创建分页对象
        Page<ManualAuditPage> page = new Page<>();
        //设置页码
        page.setCurrent(0);
        //设置行数
        page.setSize(10);
        //执行查询
        //执行查询
        manualAuditPageService.page(page,new LambdaQueryWrapper<ManualAuditPage>()
                //逻辑删除
                .eq(ManualAuditPage::getDeleteFlag,Boolean.FALSE)
        );
        page.setTotal(manualAuditPageService.count(new LambdaQueryWrapper<ManualAuditPage>()
                //逻辑删除
                .eq(ManualAuditPage::getDeleteFlag,Boolean.FALSE)
        ));
        //返回结果
        return AjaxResult.success(page);
    }



    @Resource
    SysUserMapper sysUserMapper;

    @PostMapping("/getUserData")
    public AjaxResult getUserData(){
        Boolean isa = false;

            SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
            System.out.println(888);
            System.out.println(sysUser);
            if (Objects.nonNull(sysUser)) {
                isa=true;
            }

        return AjaxResult.success(isa);
    }

    @PostMapping("/getUniappEwm")
    public AjaxResult getUniappEwm(@RequestBody BeseImg imgBase64){
        System.out.println(imgBase64);
        System.out.println(9876);
        System.out.print(imgBase64.getImgBase64());
        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode("");
        // 定义图片文件的保存路径
        String filePath = "D:/home/image.png"; // 修改为你的实际路径
        // 将字节数组写入文件
        try (OutputStream out = new FileOutputStream(filePath)) {
            out.write(imageBytes);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

       /* // 定义图片保存的目录
        String UPLOAD_DIR = "/path/to/your/upload/directory/";
        if (data.isEmpty()) {
            return AjaxResult.error("文件为空！");
        }

        try {
            // 生成唯一的文件名，避免文件名冲突
            String fileName = UUID.randomUUID().toString() + "_" + data.getOriginalFilename();
            Path filePath = Paths.get(UPLOAD_DIR, fileName);

            // 将文件保存到服务器上
            Files.write(filePath, data.getBytes());

            // 返回图片在服务器上的相对路径（或绝对路径，根据需要调整）
            String imageUrl = "/uploads/" + fileName; // 假设你的服务器配置了一个静态资源映射到/uploads/目录
//            return ResponseEntity.ok(imageUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        return AjaxResult.success();
    }

    @PostMapping("/getUniappUser")
    public AjaxResult getUserId(){
        //查询用户信息
        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        //判断查询对象不为 null
        if (Objects.nonNull(sysUser)){
            //设置对象给遍历对象
            return AjaxResult.success(sysUser);
        }else {
            //返回错误信息
            return AjaxResult.error("查询用户信息失败！");
        }

    }




    @PostMapping("/upload3")
    public String uploadTestFile3(MultipartFile file) throws Exception {
        try {
            System.out.println("nihao");
            System.out.println(file);
            // 定义存储路径和文件名https://privatedomainapi.siyu99.com/LiKLKImages/FANKUI/二维码弹窗@3x.png
//            String baseDir = "D:/abc/";   // 存储根目录D:\wwwroot\private_domain_api\wwwroot\LiKLKImages
            String baseDir = "D:/wwwroot/private_domain_api/wwwroot/LiKLKImages/invite/";   // 存储根目录D:\wwwroot\private_domain_api\wwwroot\LiKLKImages
//            String fileName = "二维码弹窗@3x.png"; // 固定文件名

// 生成 UUID 并拼接文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileName = "邀请码" + uuid + ".png";
            // 创建目标目录（若不存在）
            File dir = new File(baseDir);
            if (!dir.exists()) {
                dir.mkdirs(); // 自动创建多级目录‌:ml-citation{ref="1,2" data="citationList"}
            }

            // 保存文件到本地
            File dest = new File(baseDir + fileName);
            file.transferTo(dest); // 核心保存方法‌:ml-citation{ref="2" data="citationList"}

            // 构造返回数据
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", baseDir+fileName); // 本地绝对路径
            ajax.put("fileName", baseDir+fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
//            return AjaxResult.success(baseDir+fileName);
            return fileName;
        } catch (Exception e) {
            return "";
//            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

}
